package com.company.psm.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.company.psm.entity.User;
import com.company.psm.service.CategoryManagement;
import com.company.psm.service.UserManagement;

@Controller
@RequestMapping("/category")
public class CategoryController {
	@Autowired
	private CategoryManagement categoryManagement;
	@Autowired
	private UserManagement userManagement;
	
	@RequestMapping(method = RequestMethod.GET, value = "list")
	public ModelAndView getAll(@RequestParam(value="listAll", required=false) String listAll,
			@RequestParam(value="searchKey", required=false) String searchKey
			) {
		Long storeId = getCurrentUser().getStore().getId();
		ModelAndView model = new ModelAndView();
		model.setViewName("/category/list");
		model.addObject("categories",categoryManagement.getAllByStore(storeId));
		return model;
		
	}
	
	@RequestMapping(method = RequestMethod.GET, value = "create")
	public ModelAndView create(@RequestParam(value = "categoryName", required = false) String name,
			@RequestParam(value = "description", required = false) String description){
		Long storeId = getCurrentUser().getStore().getId();
		description = "";
		categoryManagement.careateCategory(name, description, getCurrentUser().getStore());
		ModelAndView model = new ModelAndView();
		model.setViewName("/category/list");
		model.addObject("categories",categoryManagement.getAllByStore(storeId));
		return model;

	}
	@RequestMapping(method = RequestMethod.GET, value = "update")
	public ModelAndView update(@RequestParam(value = "id", required = false) String id,
			@RequestParam(value = "updateName", required = false) String name,
			@RequestParam(value = "description", required = false) String description){
		description = "";
		Long storeId = getCurrentUser().getStore().getId();
		categoryManagement.updateCategory(id,name, description,storeId);
		ModelAndView model = new ModelAndView();
		model.setViewName("/category/list");
		model.addObject("categories",categoryManagement.getAllByStore(storeId));
		return model;

	}
    public User getCurrentUser(){
    	Authentication authentication = SecurityContextHolder.getContext().
      		  getAuthentication();
      		  String name = authentication.getName();
      	return userManagement.getUserByAccount(name);
    }
}
